package com.itcam.quicksort;

import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author : Cammy.Wu
 * Description : 
 */

public class QuickSort {
    public static void main(String[] args) {
        int[] a = {9, 5, 7, 12, 1, 3};
        System.out.println(Arrays.toString(a));
        quickSort(a, 0, a.length - 1);
        System.out.println(Arrays.toString(a));
    }

    private static void quickSort(int[] nums, int start, int end) {
        if (start >= end) return;
        int mid = partition(nums, start, end);
        quickSort(nums, mid + 1, end);
        quickSort(nums, start, mid - 1);
    }

    private static int partition(int[] nums, int left, int right) {
//        int pivot = nums[right];
//        int x = left;
//        int y = left;
//        while (y < right) {
//            if (nums[y] < pivot) {
//                if (x != y) {
//                    swap(nums, x, y);
//                }
//                x++;
//            }
//            y++;
//        }
//        swap(nums, x, right);
//        return x;
        int index = ThreadLocalRandom.current().nextInt((right - left + 1) + left);
        swap(nums, index, left);
        int pivot = nums[left];
        int x = left + 1;
        int y = right;
        while (x <= y) {
            while (x <= y && nums[x] < pivot) {
                x++;
            }
            while (x <= y && nums[y] > pivot) {
                y--;
            }
            if (x <= y) {
                swap(nums, x, y);
                x++;
                y--;
            }
        }
        swap(nums, y, left);
        return y;
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}
